<template>
  <div class="added-container">
    <el-dialog class="dialog-box" v-model="dialogVisible" :before-close="handleClose"
      ><template #header>
        <div class="my-header">
          <div>{{ state.title }}</div>
        </div>
      </template>
      <div class="check-container">
        <div class="base-info">
          <span class="base-title">基本信息：</span>
          <div class="base-body">
            <el-form ref="formRef" :model="state.addForm" label-width="auto" :rules="rules">
              <el-row class="scheme-type-box">
                <el-form-item label="考核名称" prop="scName">
                  <el-input placeholder="输入考核名称" v-model="state.addForm.scName" />
                </el-form-item>
              </el-row>
              <el-row>
                <div class="base-title">选择计算方案：</div>
              </el-row>
              <el-row class="scheme-type-box">
                <el-form-item label="计算方案类型" prop="calcscType">
                  <el-select
                    v-model="state.addForm.calcscType"
                    placeholder="请选择"
                    @change="handleChangeSchemeType"
                  >
                    <el-option :label="'区域方案'" :value="0"></el-option>
                    <el-option :label="'河系方案'" :value="1"></el-option>
                  </el-select>
                </el-form-item>
                <!-- 区域或河系 -->
                <el-form-item label="河系" prop="schemeType" v-if="state.addForm.calcscType == 1">
                  <el-select
                    v-model="state.addForm.calcZone"
                    placeholder="请选择"
                    @change="handleChangeRiverArea"
                  >
                    <el-option
                      :key="index"
                      v-for="(item, index) in state.areaRiverList"
                      :value="item.id"
                      :label="item.calczName || item.rsysName"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="区域" prop="schemeType" v-if="state.addForm.calcscType == 0">
                  <el-select
                    v-model="state.addForm.calcZone"
                    placeholder="请选择"
                    @change="handleChangeRiverArea"
                  >
                    <el-option
                      :key="index"
                      v-for="(item, index) in state.areaRiverList"
                      :value="item.id"
                      :label="item.calczName || item.rsysName"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="计算方案" prop="calcScid">
                  <el-select
                    v-model="state.addForm.calcScid"
                    placeholder="请选择"
                    @change="handleUpldateScheme"
                  >
                    <el-option
                      :key="index"
                      v-for="(item, index) in state.schemeList"
                      :value="item.id"
                      :label="item.scName"
                    />
                  </el-select>
                </el-form-item>
                <div class="btn-title" @click="handleSearchDetail">查看方案详情</div>
              </el-row>
              <el-row class="scheme-type-box">
                <el-form-item label="调度类型" prop="dispach-type">
                  <div>
                    <el-select multiple v-model="state.addForm.disTypes" placeholder="请选择">
                      <el-option
                        v-for="(item, index) in state.disTypesArr"
                        :key="index"
                        :label="item.name"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </div>
                </el-form-item>
              </el-row>
            </el-form>
          </div>
        </div>
        <!-- <div class="table-info">
          <span class="base-title">预报场次设置信息</span>
          <div class="add-session">
            <el-button type="warning" @click="handleNewSessions">新增场次</el-button>
          </div>
          <div class="table-box">
            <el-table :data="countTableData" style="width: 100%; margin-top: 10px" align="center">
              <el-table-column
                prop="playName"
                label="场次名称"
                show-overflow-tooltip
                align="center"
              />
              <el-table-column
                prop="sportTime"
                label="预报时间"
                show-overflow-tooltip
                align="center"
              />
              <el-table-column prop="day" label="预热期-天" show-overflow-tooltip align="center" />
              <el-table-column
                prop="hours"
                label="预见期-小时"
                class-name="colunmWidth"
                align="center"
              />
              <el-table-column
                prop="computTime"
                label="计算开始/结束时间"
                class-name="colunmWidth"
                show-overflow-tooltip
                align="center"
              />
              <el-table-column prop="address" label="操作" class-name="colunmWidth" align="center">
                <template #default>
                  <el-button link type="primary" size="small">修改</el-button>
                  <el-button link type="primary" size="small">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagi-nation
              :pageSize="page.pageSize"
              :pageTotal="page.total"
              @pageFunc="pageFunc"
              class="page"
            >
            </pagi-nation>
          </div>
        </div> -->
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleSaveScheme">保存方案</el-button>
          <!-- <el-button type="success" @click="handleClose"> 计算</el-button> -->
        </span>
      </template>
    </el-dialog>
    <!-- 新建场次 -->
    <!-- <newSession ref="newSess" @closeNew="handleNesClose"></newSession> -->
    <SchemeDetail ref="schemeDetailRef" />
  </div>
</template>

<script setup>
import { reactive, ref, defineExpose, watch, onUnmounted } from 'vue'
import emitter from '@/utils/bus'
import SchemeDetail from '@/pages/DispatchManage/cpns/schemeDetail/index.vue'
import {
  addArea,
  getAreaSecList,
  getAreaList,
  getRsysList,
  getSchemeList,
  getRiverScheme
} from '@/services/modules/compute-methods'
//
import { addCalcScheme, modifyCalcScheme } from '@/services/modules/model-exam'
//分页
import pagiNation from '@/components/app-pagination/pagination.vue'
import { ElMessage } from 'element-plus'
// 新建场次
// import newSession from './cpns/newSessions.vue'
const props = defineProps({
  // dialogVisible: {
  //   type: Boolean,
  //   default: false
  // },
  // checkObj: {
  //   type: Object,
  //   default: {}
  // },
  watershedId: {
    type: Number,
    default: 1
  }
})

const state = reactive({
  disTypesArr: [
    { name: '规程调度', id: 1 },
    // { name: "优化调度", id: 2 },
    // { name: "指令调度", id: 3 },
    { name: '水量平衡（不拦蓄）', id: 4 },
    { name: '蓄水（不泄洪）', id: 5 },
    { name: '现状调度', id: 6 }
  ],
  title: '新建考核',
  // 根据计算方案类型得到的区域或河系列表
  areaRiverList: [],
  // 改变河系或区域获取到的计算方案
  schemeList: [],
  secList: [],
  // 表单数据
  addForm: {
    scName: '',
    // 计算方案类型
    calcscType: '',
    // 选择的河系或区域
    calcZone: '',
    // 选择的计算方案
    calcScid: '',
    dispachType: 1
  },
  num: 0
})
let dialogVisible = ref(false)
// 兄弟组件触发事件并传值
emitter.on('updateScheme', (value) => {
  dialogVisible.value = true
  if (value.id) {
    state.title = '修改考核'
    setTimeout(() => {
      // state.addForm.calcScid = ''

      state.addForm = { ...value }
      console.log(state.addForm, '计算方案1212')
      handleChangeSchemeType(value.calcscType)
      // 选择区域或河系
      handleChangeRiverArea(value.calcZone)
      // 选中计算方案
      handleUpldateScheme(value.calcScid)
    }, 100)
  } else {
    state.addForm = {}
    // state.addForm.calcZone = ''

    state.title = '新建考核'
  }
})
onUnmounted(() => {
  emitter.off('updateScheme')
})

const formRef = ref(null)

// const newSess = ref(null)
const schemeDetailRef = ref(null)

const rules = {
  scName: [{ required: true, message: '请输入考核名称', trigger: 'blur' }],
  calcscType: [{ required: true, message: '请选择方案类型', trigger: 'blur' }],
  calcScid: [{ required: true, message: '请选择方案', trigger: 'blur' }]
}
// function
// 关闭新增考核
// const emit = defineEmits(['handleEmitClose'])
function handleClose() {
  formRef.value.resetFields()
  dialogVisible.value = false
  // emit('handleEmitClose')
}
//保存
function handleSaveScheme() {
  // addForm.schemeType1 = undefined
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 添加考核方案
      if (!state.addForm?.id) {
        addCalcScheme({ ...state.addForm, zoneId: props.watershedId }).then((res) => {
          if (res.code === 200) {
            ElMessage.success('添加成功')
            emitter.emit('resetCheck')
            handleClose()
          }
        })
      } else {
        // 修改考核方案
        modifyCalcScheme({ ...state.addForm, zoneId: props.watershedId }).then((res) => {
          if (res.code == 200) {
            ElMessage.success('修改成功')
            emitter.emit('resetCheck')

            handleClose()
          }
        })
      }
    }
  })
}
//获取所有预报断面
function getSecList() {
  getAreaSecList().then((res) => {
    if (res.code === 200) {
      state.secList = res.data
    }
  })
}
function handleOpenModal() {
  dialogVisible.value = true
  getSecList()
}
defineExpose({ handleOpenModal })
function handleSearchDetail() {
  schemeDetailRef.value.handleOpenModal({
    schemeType1: state.addForm.calcZone,
    calcScid: state.addForm.calcScid,
    calcType: state.addForm.calcscType
  })
}
// 新增场次,打开弹框
// function handleNewSessions() {
//   newSess.value.handleOpenModal()
// }
// function handleNesClose() {
//   showSessions.value = false
// }
//修改计算方案
function handleUpldateScheme(val) {
  state.addForm.calcScid = val
}
//改变计算方案类型
function handleChangeSchemeType(val) {
  state.areaRiverList = []
  // 区域
  if (val == 0) {
    getAreaList({ zoneId: props.watershedId }).then((res) => {
      if (res.code === 200) {
        state.areaRiverList = res.data
      }
    })
  } else if (val == 1) {
    // 河系
    getRsysList({ zoneId: props.watershedId }).then((res) => {
      if (res.code === 200) {
        state.areaRiverList = res.data
      }
    })
  }
}
//改变河系区域
function handleChangeRiverArea(val) {
  state.schemeList = []
  // 点击河系 默认修改进入 则不清空选中的方案 否则清空选中方案

  if (state.num > 0) {
    state.addForm.calcScid = ''
  }
  state.num++

  // 获取对应的计算方案
  if (state.addForm.calcscType == 0) {
    getSchemeList({ zid: val }).then((res) => {
      if (res.code === 200) {
        state.schemeList = res.data
      }
    })
  } else if (state.addForm.calcscType == 1) {
    getRiverScheme({ rsid: val }).then((res) => {
      state.schemeList = res.data
    })
  }
}
</script>

<style lang="less" scoped>
.scheme-type-box {
  margin-left: 30px;
}
.added-container {
  :deep(.dialog-box) {
    height: 480px;
    overflow: auto;
  }
  :deep(.el-input) {
    width: 200px;
  }
  .btn-title {
    height: 30px;
    color: #409eff;
    display: flex;
    align-items: center;
    margin-left: 30px;
    cursor: pointer;
  }
  .my-header {
    height: 35px;
    border-bottom: 2px solid #eee;
  }
  .check-container {
    .base-title {
      display: inline-block;
      color: #409eff;
    }
    // .table-info {
    //   .add-session {
    //     display: flex;
    //     // height: 40px;
    //     justify-content: flex-end;
    //     align-items: center;
    //   }
    //   .table-box {
    //     .page {
    //       display: flex;
    //       justify-content: flex-end;
    //       margin-top: 10px;
    //     }
    //   }
    // }
    // .base-info {

    // }
  }
}
</style>
